package pers.lx.crm.service.info.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.lx.crm.base.common.pigeon.Result;
import pers.lx.crm.base.constant.ErrorConstant;
import pers.lx.crm.base.constant.KeyConstants;
import pers.lx.crm.base.util.ResultUtil;
import pers.lx.crm.dao.info.TagBlockDao;
import pers.lx.crm.dao.info.TemplateDao;
import pers.lx.crm.entiy.info.TagBlockDO;
import pers.lx.crm.entiy.info.TemplateDO;
import pers.lx.crm.service.info.TemplateService;

import java.util.List;

/**
 * Created by lx on 2017/3/6.
 */
@Service
public class TemplateServiceImpl implements TemplateService {

    @Autowired
    private TemplateDao templateDao ;

    @Autowired
    private TagBlockDao tagBlockDao ;

    @Override
    public Result getTemplates(TemplateDO templateDO) {
        Result result = new Result() ;
        try {
           templateDO.setList(templateDao.selectTemplateListPage(templateDO));
            return ResultUtil.getPageResult(templateDO,result) ;
        } catch (Exception e){
            e.printStackTrace();
            result.setError(ErrorConstant.UNKNOWN_ERROR);
        }
        return result;
    }

    @Transactional
    @Override
    public Result addTemplate(TemplateDO templateDO) {
        Result result = new Result() ;
        templateDao.insertTemplate(templateDO);
        for (TagBlockDO tagBlockDo:templateDO.getTagBlocks()){
            templateDao.insertTemplateInfo(templateDO.getId(),tagBlockDo.getId());
        }
        return result;
    }

    @Transactional
    @Override
    public Result updateTemplate(TemplateDO templateDO) {
        Result result = new Result() ;
        templateDao.updateTemplate(templateDO);
        templateDao.deleteTemplateInfo(templateDO.getId());
        for (TagBlockDO tagBlockDo:templateDO.getTagBlocks()){
            templateDao.insertTemplateInfo(templateDO.getId(),tagBlockDo.getId());
        }
        return result;
    }

    @Transactional
    @Override
    public Result removeTemplate(List<TemplateDO> templateDOs) {
        Result result = new Result() ;
        for (TemplateDO templateDo:templateDOs){
            templateDao.deleteTemplateInfo(templateDo.getId());
            templateDao.deleteTemplate(templateDo.getId());
        }
        return result;
    }

    @Override
    public Result getTagsBlock(TemplateDO templateDO) {
        Result result = new Result() ;
        List<TagBlockDO> tagBlockDOs = templateDao.selectTagBlocks(templateDO.getId()) ;
        for(TagBlockDO tagBlockDO:tagBlockDOs){
            tagBlockDO.setTags(tagBlockDao.selectTagList(tagBlockDO.getId()));
        }
        result.addParam(KeyConstants.LIST_KEY,tagBlockDOs);
        return result;
    }
}
